package com.zky.gulimall.seckill.schedule;

import com.zky.gulimall.seckill.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Description 秒杀商品定时上架缓存
 * @Author 张开源
 * @Date 2022/12/26 12:55
 * @Version 1.0
 **/
@Service
@Slf4j
public class SecKillSkuScheduled {
    @Autowired
    private SecKillService secKillService;
    @Autowired
    private RedissonClient redissonClient;

    private static final String UPLOAD_LOCK = "secKill:upload:lock:";

    //0 0/30 * * * ?
    @Scheduled(cron = "0 0/10 * 1/1 * ? ")
    public void uploadSecKillSkuLatest3Days() {
        log.warn("商品上架开始------------------------------>");

        //加分布式锁，同一段时间只有一个机器执行相关代码
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            secKillService.uploadSecKillSkuLatest3Days();
        } finally {
            lock.unlock();
        }
        log.warn("商品上架结束------------------------------>");
    }
}
